package com.learning.spring.data.transaction.code.service.impl;

import com.learning.spring.data.transaction.code.entity.User;
import com.learning.spring.data.transaction.code.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.StatementCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * ClassName: UserServiceImpl
 * Description:
 * Date: 2020/7/22 16:19 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private TransactionTemplate transactionTemplate;

    /**
     * TransactionTemplate 事务访问模板
     * 模板设计模式
     *
     * @param user
     * @return
     */
    @Override
    public int add(User user) {

        int result = transactionTemplate.execute(new TransactionCallback<Integer>() {
            @Override
            public Integer doInTransaction(TransactionStatus status) {
                // 可以根据 TransactionStatus 事务状态处理事务的提交与回滚等
                // 数据库操作

                // 捕获异常，事务不会回滚
                try {
                    int i = 1 / 0;
                } catch (Exception e) {

                }

                // 设置回滚
                status.setRollbackOnly();

                // 抛出异常，事务回滚
                int i = 1 / 0;

                return 1;
            }
        });
        return result;
    }


    /**
     * JDBC 模板操作数据
     *
     * @param id
     * @return
     */
    @Override
    public int delete(int id) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.execute(new StatementCallback() {
            @Override
            public Object doInStatement(Statement stmt) throws SQLException, DataAccessException {
                // 执行业务数据操作
                ResultSet resultSet = stmt.executeQuery("SELECT * FROM t_user WHERE ?");
                return null;
            }
        });

        return 0;
    }

    @Override
    public int update(User user) {
        return 0;
    }

    @Override
    public User select(int id) {
        return null;
    }
}
